package org.huoran.sakamichi.study.S_20170608_volatile;

import java.util.concurrent.CountDownLatch;

public class VolatileStudy {

    /**
     * 脏读测试
     * volatile关键字修饰变量为必须从主存获取，写后立刻更新主存。
     * 若并发场景某n个线程同时读主存并写回则造成同步错误。
     * 20线程各执行20000次期望400000，结果小于400000。
     */
    public static class DirtyReadTest {
        private volatile int race = 0;
        private int THREADS_COUNT = 20;
        private CountDownLatch latch = new CountDownLatch(THREADS_COUNT);

        private void increase() {
            race++;
        }

        public void start () {
            Thread[] threads = new Thread[THREADS_COUNT];
            for (int i = 0; i < THREADS_COUNT; i++) {
                threads[i] = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (int j = 0; j < 20000; j++) {
                            increase();
                        }
                        latch.countDown();
                    }
                });
                threads[i].start();
            }
            try{
                latch.await();
                System.out.println(race);
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args){
        DirtyReadTest dirtyReadTest = new DirtyReadTest();
        dirtyReadTest.start();
    }
}